package com.wrk._2_数组._02_习题;

import java.util.Arrays;

public class _011_验证歌德巴赫猜想 {
    public static void main(String[] args) {
        int max = 20;
        int [] generatingPrimes = new int[max];
        //1、找出所有2-20之间素数，输出为数组
            //求素数素组长度，并赋值
        int count = 0;
        int count2 = 0;
        for (int number1 =2; number1 <= max; number1++){
            for (int number2 = 2;number2 <= number1; number2++){
                if (number1 % number2 == 0){
                    count++;
                }
            }
            //素数数组赋值
            if (count ==1){
                generatingPrimes[count2++] = number1;
                count =0;
            }else {
                count = 0;
            }
        }
        //定义素数数组
        int [] primeNumberArray = Arrays.copyOf(generatingPrimes,count2);
        System.out.println("打印素数数组："+Arrays.toString(primeNumberArray));

        //2、找出6-20之间所有偶数，输出为数组
        int count1 = 0;
            //求偶数数组长度
        for ( int min = 6; min <= max;min += 2){
            count1++;
        }
            //定义偶数数组
        int [] evenArray = new int[count1];
            //给偶数数组赋值
        for (int i = 0; i < evenArray.length; i++) {
            evenArray[i] = 6 + 2*i;
        }
        System.out.println("打印偶数数组："+Arrays.toString(evenArray));

        //3、判断每一个偶数是否可分解为两个素数之和
            //遍历偶数数组
        System.out.println("验证结果如下：");
        for (int even : evenArray) {
            boolean foul = false;
                //遍历素数数组，求和是否相等
            for (int j = 0; j < primeNumberArray.length; j++) {
                for (int k = j; k < primeNumberArray.length; k++) {
                    if (primeNumberArray[j] + primeNumberArray[k] == even){
                        System.out.println(even+"="+primeNumberArray[j]+"+"+primeNumberArray[k]);
                        foul = true;
                        break;
                    }
                }
                //找到第一个合法解，已经验证了当前偶数 even 的哥德巴赫猜想成立，无需继续检查其他素数组合，跳出循环
                if (foul) break;
            }
        }
    }
}
